import Vue from "vue";
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'

Vue.use(VueRouter)

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function(location,resolve,reject){
    if(resolve && reject){
        originPush.call(this,location,resolve,reject)
    }else{
        originPush.call(this,location,()=>{},()=>{})
    }
}
VueRouter.prototype.replace = function(location,resolve,reject){
    if(resolve && reject){
        originReplace.call(this,location,resolve,reject)
    }else{
        originReplace.call(this,location,()=>{},()=>{})
    }
}

let router = new VueRouter({
    routes,
    //滚动行为
    scrollBehavior (to, from, savedPosition) {
        return  {y:0}
    }
})
//配置路由守卫
router.beforeEach(async (to,from,next) =>{
    let token = store.state.user.token
    let name = store.state.user.userInfo.name
    if(token){
        //已登录
        if(to.path == '/login'){
            //让用户不再去登录界面
            next('/home')
        }else{
            //去的不是login
            if(name){
                next()
            }else{
                try {
                    //这一步是为了获取用户信息，token一直都有，因为已经存到了本地，
                    //但是userInfo一刷新就会没有，需要再次派发getUserInfo
                    await store.dispatch('getUserInfo');
                    next(); 
                } catch (error) {
                    //token失效的处理方法
                    alert('登录信息失效')
                    store.dispatch('userLogout');
                    next('/login')
                }
            }  
        }
    }else{
        //未登录,不能去pay/paysucess
        let toPath = to.path
        if(to.path.indexOf('/trade')!==-1||to.path.indexOf('/pay')!==-1||to.path.indexOf('/center')!==-1){
            next("/login?redirect="+toPath)
        }else{
            next()
        }        
    }
    
})
export default router